<template>
    <el-form ref="loginFrom" :model="loginFromData" status-icon :rules="commonRules" label-width="60px"
        class="demo-loginFromData">
        <el-form-item label="用户名" prop="username" class="username-from-item">
            <el-input v-model="loginFromData.username" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input v-model="loginFromData.password" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="验证码" prop="captcha" class="captcha it">
            <el-input class="captcha-content" v-model="loginFromData.captcha" maxlength="5"
                @keydown.enter="submitForm(loginFrom)" />
            <span class="oi" v-loading="loading">
                <i v-html="captcha" @click="getCaptcha"></i>
            </span>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="submitForm(loginFrom)" class="submit-style">提交</el-button>
        </el-form-item>
    </el-form>

</template>


<script setup>
import { reactive, ref, onMounted, onUnmounted } from 'vue'
// 引入校验函数
import { commonRules, useSubmitForm } from "../../composition/login/validate";
// 引入接口
// import * as api from "@/api.users.js"
import * as api from "../../api/users"
// 引入路由对象
import { useRouter } from "vue-router"
// 引入 store
import { userUser } from "@/store/users.js"
// 引入 loading 加载动画
import { ElLoading } from 'element-plus'

// 使用store
let useStore = userUser()

// 使用路由对象
let router = useRouter()
// 表单校验成功后 回调的方法

let validateSuccess = () => {
    // console.log("校验成功");
    // 发起登入请求
    // 1.登入请求前要先校验验证码
    verifyCaptcha(loginFromData.captcha.toLowerCase())

}

// 表单校验失败  回调的方法

let validateFailed = () => {
    console.log("校验失败");
}



// 使用useSubmitForm
let submitForm = useSubmitForm(validateSuccess, validateFailed)

const loginFrom = ref()




// 注入到表单的数据

const loginFromData = reactive({
    username: '',
    password: '',
    captcha: '',
})
let loading = ref(true)

// 声明一个展示验证码的响应式变量
let captcha = ref()
// 测试接口
let getCaptcha = async () => {
    loading.value = true
    let res = await api.getcaptchaApi()
    // console.log(res,"asdasd");
    loading.value = false
    // 判断是否请求成功
    if (res.data.state) {
        captcha.value = res.data.img
    }
}





// 首次加载时调用
onMounted(() => {
    getCaptcha()
})


//校验验证码
// 1.本地表单校验通过之后
// 2.通过接口校验验证码

// 为了让两个请求都能拿到 loading加载动画 外部声明一个 loadingInstance

let loadingInstance = null;

let verifyCaptcha = async captcha => {
    // 在发起登录请求时 就要加载 loading登入动画
    loadingInstance = ElLoading.service({
        lock: true,
        text: "登录中..."
    })

    try {
        let res = await api.verifycaptchaApi(captcha)
        login(loginFromData.username, loginFromData.password)
    } catch (e) {
        console.log(e);
        getCaptcha()
        console.log(captcha);
        loginFromData.captcha = ''
        // 关闭loading加载动画
        loadingInstance.close()
    }

}

// 用户名密码登入逻辑

/**
 * 描述
 * @date 2022-12-01
 * @param {String} username 用户名
 * @param {Number} password 密码
 * @returns {any}
 */
let login = async (username, password) => {

    try {
        // 调用登录请求的 Api
        let res = await api.LoginApi(username, password)
        console.log(res);
        // 存储 token
        sessionStorage.setItem("data", res.data.token)
        // 存储用户信息
        useStore.$patch({ userInfo: res.data.userInfo })
        useStore.$patch({ permission: res.data.permission })
        // 在登录成功后需要跳转到主页 编程式导航引入路由对象
        router.push("/")
        // 跳转后关闭加载loading
        loadingInstance.close()

    } catch (e) {
        console.log(e);
        loadingInstance.close()
    }
}

onUnmounted(() => {
    // 如果它存在就把它关闭
    loadingInstance && loadingInstance.close()
})
</script>

<style lang="less">
.submit-style {
    width: 250px;
}


.it {

    .oi {
        width: 125px;
        height: 40px;
        background-color: #FFFFFF;
        border-radius: 0 5px 5px 0;
        cursor: pointer;
    }

    .el-input__wrapper {
        border-radius: 5px 0 0 5px;
    }
}


svg {
    position: relative;
    bottom: 4px;
    right: 12px;
}

.captcha-content {
    width: 125px;
    height: 40px;
    // background-color: aqua;
    position: relative;

}

.el-input__wrapper {
    box-shadow: none !important;
    height: 38px;
}
</style>